package com.yanqu.road.server.manger.zhaoshang;

import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.player.UserDecorationInfoResult;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogZsProjectSeatExpel;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.UserRank;
import com.yanqu.road.entity.servercenter.CrossServerGroup;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.servercenter.TitleInfo;
import com.yanqu.road.entity.zhaoshang.ZsTopOfRank;
import com.yanqu.road.entity.zhaoshang.ZsWarReport;
import com.yanqu.road.entity.zhaoshang.enums.eZsReportType;
import com.yanqu.road.logic.bussiness.zhaoshang.ZhaoShangBussiness;
import com.yanqu.road.logic.pb.CrossGroupPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.ZhaoShangPb;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.zhaoshang.ZhaoShangProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.gameplayer.module.zhaoshang.ZsModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.CrossServerGroupMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.TitleMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.util.ConcurrentHashSet;

import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 城郊-招商
 */
public class ZsMgr extends TempMgr {

    protected static Logger log = LogManager.getLogger(ZsMgr.class.getName());

    //weekId,rankType
    private static Map<Integer, Map<Integer, ZsTopOfRank>>   weekTopRankMap;       //周榜首
    //暂放配置
    public static final  int ZS_WEEK_RANK_WORSHIP_TIME_LIMIT = 1;        //每周榜单膜拜次数

    //需要上传基本信息的玩家
    private static Set<Long> needUploadUserInfoSet = new ConcurrentHashSet<>();

    @Override
    public boolean save() {
        for(int weekId : weekTopRankMap.keySet()){
            Map<Integer, ZsTopOfRank> typeMap = weekTopRankMap.get(weekId);
            for(int type : typeMap.keySet()){
                ZsTopOfRank userRank = typeMap.get(type);
                if(userRank.isInsertOption()){
                    ZhaoShangBussiness.addWeekTopRank(userRank);
                }
            }
        }
        return true;
    }

    @Override
    public boolean reload() throws Exception {
        int preWeekId = getPreWeekId();
        weekTopRankMap = ZhaoShangBussiness.getWeekTopRankMap(preWeekId);
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        addServerGroupReloadListener();
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    //前一周id
    public static int getPreWeekId() {
        Calendar now = Calendar.getInstance();
        Date monday = DateHelper.getThisWeekMonday(now.getTime());
        now.setTime(monday);
        now.add(Calendar.HOUR, -7 * 24);
        return Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
    }

    //本周id
    public static int getThisWeekId(){
        Calendar now = Calendar.getInstance();
        Date monday = DateHelper.getThisWeekMonday(now.getTime());
        now.setTime(monday);
        return Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
    }

    public static boolean addWarReport(ZsWarReport zsWarReport) {
        return ZhaoShangBussiness.addZsWarReport(zsWarReport);
    }

    //玩家周收益变更，上传跨服
    public static void userRankChange(UserRank userRank){
        ZhaoShangProto.CrossZsWeekRankChangeReqMsg.Builder rankMsg = ZhaoShangProto.CrossZsWeekRankChangeReqMsg.newBuilder();
        int weekId = getThisWeekId();
        rankMsg.setWeekId(weekId);
        ZhaoShangProto.ZsWeekRankTemp.Builder builder = ZhaoShangPb.parseZsWeekRankTemp(userRank);
        rankMsg.addDataList(builder);
        YanQuMessage pbMessage = YanQuMessageUtils.buildMessage(Protocol.C_ZHAO_SHANG_RANK_CHANGE, rankMsg);
        GamePlayerMgr.sendPacket(0, pbMessage);
    }

    //玩家周收益变更，上传跨服
    public static void userRankChange(List<UserRank> userRankList){
        ZhaoShangProto.CrossZsWeekRankChangeReqMsg.Builder rankMsg = ZhaoShangProto.CrossZsWeekRankChangeReqMsg.newBuilder();
        int weekId = getThisWeekId();
        rankMsg.setWeekId(weekId);
        for(UserRank userRank : userRankList) {
            ZhaoShangProto.ZsWeekRankTemp.Builder builder = ZhaoShangPb.parseZsWeekRankTemp(userRank);
            rankMsg.addDataList(builder);
        }
        YanQuMessage pbMessage = YanQuMessageUtils.buildMessage(Protocol.C_ZHAO_SHANG_RANK_CHANGE, rankMsg);
        GamePlayerMgr.sendPacket(0, pbMessage);
    }

    //是否是系统开放时间
    public static boolean isZsSystemOpenTime(){
        boolean open = false;
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        if(serverInfo != null) {
            int days = DateHelper.calc2DateTDOADays(new Date(serverInfo.getOpenTime() * 1000), new Date());
            open = days >= serverInfo.getOpenZsDay();
        }
        CrossServerGroup serverGroup = CrossServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        boolean groupOpen =  serverGroup == null ? false : serverGroup.getCrossZsState() == 1;
        return open || groupOpen;
    }

    //获取榜首
    public static Map<Integer, ZsTopOfRank> getTopRankMap(int weekId){
        if(weekTopRankMap.containsKey(weekId)){
            return weekTopRankMap.get(weekId);
        }
        return null;
    }

    //请求跨服榜首
    public static void getPreWeekRankTopFromCross() {
        int preWeekId = getPreWeekId();
        if(!weekTopRankMap.containsKey(preWeekId)){
            ZhaoShangProto.CrossZsWeekRankTopReqMsg.Builder reqMsg = ZhaoShangProto.CrossZsWeekRankTopReqMsg.newBuilder();
            reqMsg.setWeekId(preWeekId);
            YanQuMessage pbMessage = YanQuMessageUtils.buildMessage(Protocol.C_ZHAO_SHANG_PROJECT_TOP_OF_RANK, reqMsg);
            GamePlayerMgr.sendPacket(0, pbMessage);
        }
    }

    //来自跨服的榜首数据
    public static void syncPreWeekRankTopFromCross(int weekId, List<ZsTopOfRank> list) {
        boolean change = false;
        synchronized (weekTopRankMap){
            if(!weekTopRankMap.containsKey(weekId)){
                weekTopRankMap.put(weekId, new ConcurrentHashMap<>());
            }
            for(ZsTopOfRank topRank : list){
                if(!weekTopRankMap.get(weekId).containsKey(topRank.getRankType())){
                    topRank.setInsertOption();
                    weekTopRankMap.get(weekId).put(topRank.getRankType(), topRank);
                    change = true;
                }
            }
        }
        if(change){
            //有榜首更新要重新推送玩家数据，影响膜拜红点
            List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
            for(GamePlayer onlinePlay : playerList) {
                if (onlinePlay.getState() == PlayerState.ONLINE) {
                    onlinePlay.getModule(ZsModule.class).sysZsUserData();
                }
            }
        }
    }

    //获得称号加成
    public static int getDecorationAddition(int decorationId){
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(decorationId);
        if(goodsInfo == null){
            return 0;
        }
        List<Integer> list = StringUtils.stringToIntegerList(goodsInfo.getExtendParam(), "\\|");
        if(list.size() < 6){
            return 0;
        }
        return list.get(5);
    }

    //身份加成
    public static int getTitleAddition(int titleId){
        TitleInfo titleInfo = TitleMgr.getTitleInfo(titleId);
        if(titleInfo != null){
            return titleInfo.getZsAddition();
        }
        return 0;
    }

    //被打日志（占位中）
    public static void addLogZsProjectSeatExpel(ZsWarReport zsWarReport) {
        int myClass = GoodsMgr.getUserDecorationClass(zsWarReport.getUserBaseInfo().getDecoration());
        //修正称号过期未传递到战报的bug
        if(zsWarReport.isDecorationOver()){
            myClass = -1;
        }
        int openUserDecorationClass = GoodsMgr.getUserDecorationClass(zsWarReport.getOpenDecoration());
        int enemyClass = GoodsMgr.getUserDecorationClass(zsWarReport.getEnemyBaseInfo().getDecoration());
        if(zsWarReport.getType() == eZsReportType.Fail.getIntValue()){
            //被驱逐日志
            AutoLogMgr.add(new LogZsProjectSeatExpel(zsWarReport.getUserId(), myClass, zsWarReport.getUserBaseInfo().getTitleId(), zsWarReport.getUserBaseInfo().getPrestige(),
                    zsWarReport.getEnemyUserId(), enemyClass, zsWarReport.getEnemyBaseInfo().getTitleId(), zsWarReport.getEnemyBaseInfo().getPrestige(), true, (long) zsWarReport.getAddTime() * 1000,
                    zsWarReport.getOpenUserId(), openUserDecorationClass, zsWarReport.getOpenTitleId()));

            //被驱逐邮件
            String serverName = "";
            ServerInfo serverInfo = ServerListMgr.getServerInfo(zsWarReport.getEnemyBaseInfo().getServerId());
            if(serverInfo != null){
                serverName = serverInfo.getServerName();
            }
            boolean sameServer = zsWarReport.getEnemyBaseInfo().getServerId() == GameServer.getInstance().getServerId();
            String city = zsWarReport.getEnemyBaseInfo().getCity();
            TitleInfo titleInfo = TitleMgr.getTitleInfo(zsWarReport.getEnemyBaseInfo().getTitleId());
            String language = UserMgr.getUserInfo(zsWarReport.getUserId()).getLanguage();
            String titleName = StringUtils.format(MultipleLanguageMgr.getContent("Player_Identity-" + titleInfo.getTitleId(), language), city);
            titleName = "【" + titleName + "】";
            String projectName = MultipleLanguageMgr.getContent("Zs_Project_Name-" + zsWarReport.getTemplateId(), language);
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.ZHAOSHANG_PROJECT_SEAT_EXPEL_TITLE, language);
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ZHAOSHANG_PROJECT_SEAT_EXPEL_CONTENT, language),
                    (sameServer ? titleName: serverName), zsWarReport.getEnemyBaseInfo().getNickName(), projectName);
            MailManager.sendMail(zsWarReport.getUserId(), 0, eMailType.DAILY.getValue(), "", mailContent, mailTitle, new Date());

        }else if(zsWarReport.getType() == eZsReportType.Win.getIntValue()){
            //被驱逐日志(未成功)
            AutoLogMgr.add(new LogZsProjectSeatExpel(zsWarReport.getUserId(), myClass, zsWarReport.getUserBaseInfo().getTitleId(), zsWarReport.getUserBaseInfo().getPrestige(),
                    zsWarReport.getEnemyUserId(), enemyClass, zsWarReport.getEnemyBaseInfo().getTitleId(), zsWarReport.getEnemyBaseInfo().getPrestige(), false, (long) zsWarReport.getAddTime() * 1000,
                    zsWarReport.getOpenUserId(), openUserDecorationClass, zsWarReport.getOpenTitleId()));
        }
    }

    //分组变更造成的系统开启
    private void addServerGroupReloadListener(){
        CrossServerGroupMgr.addReloadListener(new ManagerReloadListener() {
            @Override
            public void notifyReload() {
                log.info("zs serverGroup reload");
                ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
                List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
                for(GamePlayer onlinePlay : playerList){
                    if(onlinePlay.getState() == PlayerState.ONLINE) {
                        onlinePlay.getModule(ZsModule.class).crossServerGroupReload();
                        if(null != serverInfo) {
                            onlinePlay.sendPacket(Protocol.U_CROSS_GROUP_SYNC_NEW, CrossGroupPb.parseCrossGroupTypeListMsg(CrossServerGroupMgr.getServerGroupList(serverInfo.getChannelId())));
                        }
                    }
                }
            }
        });
    }

    //招商分组
    public static int getGroupId(long serverId) {
        CrossServerGroup serverGroup = CrossServerGroupMgr.getServerGroupByServerId(serverId);
        if(serverGroup != null && serverGroup.getCrossZsState() == 1){
            return serverGroup.getGroupId();
        }
        return (int)serverId;
    }


    public static void addNeedUploadUserInfo(GamePlayer player){
        //玩家是否有解锁
        if(!SystemOpenMgr.systemOpen(player, eSystemId.ZhaoShang.getValue())){
            return;
        }
        //系统是否开放
        if(!ZsMgr.isZsSystemOpenTime()){
            return;
        }
        synchronized (needUploadUserInfoSet){
            needUploadUserInfoSet.add(player.getUserId());
        }
    }

    public static Set<Long> getNeedUploadUserInfoSet() {
        return needUploadUserInfoSet;
    }

    public static void uploadUserInfo(){
        List<Long> list = new ArrayList<>();
        synchronized (needUploadUserInfoSet) {
            Iterator<Long> iterator = needUploadUserInfoSet.iterator();
            while (iterator.hasNext()) {
                list.add(iterator.next());
            }
            needUploadUserInfoSet.clear();
        }
        if(list.size() > 0){
            for (long uid : list) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(uid);
                if(player == null){
                    continue;
                }
                uploadUserInfo(player);
            }
        }
    }

    public static void uploadUserInfo(GamePlayer player) {
        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());

        UserDecorationInfoResult result = player.getModule(DecorationModule.class).getCurMaxDecorationInfo();
        int decorationClass = result.decorationClass;
        int decorationId = result.decorationId;
        long decorationOverTime = result.decorationOverTime;
        //称号加成
        int decorationAddition = getDecorationAddition(decorationId);

        ZhaoShangProto.CrossZsPlayBaseInfoSyncMsg.Builder syncReqMsg = ZhaoShangProto.CrossZsPlayBaseInfoSyncMsg.newBuilder();
        syncReqMsg.setUserBaeInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        syncReqMsg.setAddition(decorationAddition);
        syncReqMsg.setDecorationClass(decorationClass);
        syncReqMsg.setTitleAddition(ZsMgr.getTitleAddition(player.getTitleId()));
        syncReqMsg.setDecorationOverTime(decorationOverTime);
        player.sendPacket(Protocol.C2_ZHAO_SHANG_USER_INFO_SYNC, syncReqMsg);
    }
}
